package org.yunai.swjg.server.module.idSequence;

import org.yunai.swjg.server.entity.IdSequenceEntity;
import org.yunai.yfserver.spring.BeanManager;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 数据库表自增ID工具
 * User: yunai
 * Date: 13-3-30
 * Time: 下午3:37
 */
//@Component
// TODO 想办法在把DBIdSequence折腾的好点 有点乱- -！
// TODO 会有问题，并发大的时候，想下怎么改好。
public class IdSequenceHolder {

    private static IdSequenceMapper idSequenceMapper;
    static {
        IdSequenceHolder.idSequenceMapper = BeanManager.getBean(IdSequenceMapper.class);
    }

    /**
     * common_user自增ID TODO 坐等改了
     */
    public static final AtomicInteger COMMON_USER_ID = new AtomicInteger(200001);
    private static IdSequence itemIdSequence;
    private static IdSequence playerIdSequence;
    private static IdSequence doingQuestSequence;
    private static IdSequence finishedQuestSequence;
    /**
     * 怪物编号，每次服务器重启，都从1开始重新计算，无实际业务用处，只是用来标记怪物唯一性
     */
    private static final AtomicInteger MONSTER_ID = new AtomicInteger(1);

    public static synchronized void init() {
        List<IdSequenceEntity> idSequenceEntityList = idSequenceMapper.selectIdSequenceEntityList();
        for (IdSequenceEntity entity : idSequenceEntityList) {
            IdSequence sequence = new IdSequence();
            sequence.fromEntity(entity);
            switch (sequence.getId()) {
                case "gs_item": itemIdSequence = sequence; break;
                case "gs_player": playerIdSequence = sequence; break;
                case "gs_doing_quest": doingQuestSequence = sequence; break;
                case "gs_finished_quest": finishedQuestSequence = sequence; break;
                default: throw new RuntimeException(sequence.getId() + "未初始化！");
            }
        }
    }

    /**
     * @return 道具编号
     */
    public static int genItemId() {
        return itemIdSequence.genSeq();
    }

    /**
     * @return 玩家编号/伙伴编号。该编号比较特殊，公用。
     */
    public static int genPlayerOrPartnerId() {
        return playerIdSequence.genSeq();
    }

    /**
     * @return 玩家进行中的任务编号
     */
    public static int genDoingQuestId() {
        return doingQuestSequence.genSeq();
    }

    /**
     * @return 玩家完成的任务编号
     */
    public static int genFinishedQuestId() {
        return doingQuestSequence.genSeq();
    }

    /**
     * @return 怪物编号
     */
    public static int genMonsterId() {
        return MONSTER_ID.getAndIncrement();
    }
}
